package cn.wolfcode.p2p.base.service.impl;

import cn.wolfcode.p2p.base.domain.UserInfo;
import cn.wolfcode.p2p.base.mapper.UserInfoMapper;
import cn.wolfcode.p2p.base.service.IUserInfoService;
import cn.wolfcode.p2p.base.util.BitStateUtil;
import cn.wolfcode.p2p.base.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserInfoServiceImpl implements IUserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public void update(UserInfo entity) {
        int rows = userInfoMapper.updateById(entity);
        if (rows == 0) {
            throw new RuntimeException("乐观锁失败:Account.id" + entity.getId());
        }
    }

    @Override
    public UserInfo getCurrent() {
        return userInfoMapper.selectById(UserContext.getCurrentUser().getId());
    }

    @Override
    public void saveBasicInfo(UserInfo vo) {
        // 不能直接增加或跟新,会对不相关的数据造成不安全
        // 1.查询出当前的用户的基本资料对象
        UserInfo current = this.getCurrent();
        // 2.设置相关的数据(数据字典)
        current.setEducationBackground(vo.getEducationBackground())
                .setMarriage(vo.getMarriage())
                .setHouseCondition(vo.getHouseCondition())
                .setKidCount(vo.getKidCount())
                .setIncomeGrade(vo.getIncomeGrade());
        ;
        // 3.增加已经填写的基本资料的状态码
//        long state = BitStateUtil.addState(current.getBitState(), BitStateUtil.OP_BASIC_INFO);
//        current.setBitState(state);
        Long newState = current.getNewState(BitStateUtil.OP_BASIC_INFO);
        current.setBitState(newState);
        // 4.更新
        this.update(current);
    }

    @Override
    public UserInfo get(Long id) {
        return  userInfoMapper.selectById(id);
    }
}
